package com.codeplay.service.impl;

import com.codeplay.entity.Chapter;
import com.codeplay.repository.ChapterRepository;
import com.codeplay.service.ChapterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
public class ChapterServiceImpl implements ChapterService {

    private final ChapterRepository chapterRepository;

    @Autowired
    public ChapterServiceImpl(ChapterRepository chapterRepository) {
        this.chapterRepository = chapterRepository;
    }

    @Override
    public Chapter createChapter(Chapter chapter) {
        return chapterRepository.save(chapter);
    }

    @Override
    public Chapter getChapterById(Long id) {
        return chapterRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("Chapter not found"));
    }

    @Override
    public List<Chapter> getChaptersByCourseId(Long courseId) {
        return chapterRepository.findByCourseIdOrderByOrderIndexAsc(courseId);
    }

    @Override
    public Chapter updateChapter(Chapter chapter) {
        Chapter existingChapter = getChapterById(chapter.getId());
        existingChapter.setTitle(chapter.getTitle());
        existingChapter.setDescription(chapter.getDescription());
        existingChapter.setOrderIndex(chapter.getOrderIndex());
        return chapterRepository.save(existingChapter);
    }

    @Override
    public void deleteChapter(Long id) {
        chapterRepository.deleteById(id);
    }

    @Override
    public Chapter getNextChapter(Long courseId, Integer currentOrderIndex) {
        return chapterRepository.findByCourseIdAndOrderIndex(courseId, currentOrderIndex + 1);
    }

    @Override
    public Chapter getPreviousChapter(Long courseId, Integer currentOrderIndex) {
        return chapterRepository.findByCourseIdAndOrderIndex(courseId, currentOrderIndex - 1);
    }
} 